package com.zgg.core.utils

import io.vertx.core.AsyncResult
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine


/**
 * 等待一个异步函数返回，并返回其回调参数作为结果
 */
suspend fun <T> awaitFor(block: ((T) -> Unit) -> Unit): T {
    return suspendCoroutine { c ->
        block {
            c.resume(it)
        }
    }
}

/**
 * 等待一个异步函数返回，解包其AsyncResult，若成功则正常返回，失败则抛异常
 */
suspend fun <T> awaitResult(block: ((AsyncResult<T>) -> Unit) -> Unit): T {
    val ret = awaitFor(block)
    return if (ret.succeeded()) ret.result() else throw ret.cause()
}